var prefix = "/product/centre";
var prefixRestaurant = "/product/restaurant";
var flag;
$(function () {
    flag = $("#flag").val();
    load();
    // get_goods();
});

function renderCategoryThird2(obj) {
    var index = obj.options[obj.selectedIndex].value;
    var html = "<option value=''>请选择下级分类</option>";
    if (index == 0) {
        $("#ccate").html(html);
    } else {
        $.ajax({
            url: "/category/manage/getChildByPar",
            data: {"id": index},
            dataType: "json",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].name+"("+data[i].typeName + '</option>';
                }
                $("#ccate").html(html);
            }
        })
    }
}

function load() {
    $('#productTable').bootstrapTable({
        method: 'get', // 服务器数据的请求方式 get or post
        url: prefix + "/productCentrelist", // 服务器数据的加载地址
        showRefresh: true,
        // showToggle : true,
        iconSize: 'outline',
        // toolbar: '#exampleToolbar',
        striped: true, // 设置为true会有隔行变色效果
        dataType: "json", // 服务器返回的数据类型
        pagination: true, // 设置为true会在底部显示分页条
        pageList: [10, 20, 50],
        // queryParamsType : "limit",
        // //设置为limit则会发送符合RESTFull格式的参数
        singleSelect: false, // 设置为true将禁止多选
        // contentType : "application/x-www-form-urlencoded",
        // //发送到服务器的数据编码类型
        pageSize: 10, // 如果设置了分页，每页数据条数
        pageNumber: 1, // 如果设置了分布，首页页码
        // search : true, // 是否显示搜索框
        showColumns: true, // 是否显示内容下拉框（选择显示的列）
        sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者
        // "server"
        queryParams: function (params) {
            return {
                limit: params.limit,
                offset: params.offset,
                startDate: $.trim($("#startDate").val()),
                endDate: $.trim($("#endDate").val()),
                title: $.trim($("#productName").val()),
                status: $.trim($("#type").val()),
                pcate: $.trim($("#pcateId").val()),
                ccate: $.trim($("#ccateId").val()),
                supplierId: $.trim($("#supply").val()),
                centreId: $("*[name='centreId']").val(),
                //baseId: $.trim($("#baseId").val()),
                upStartTime: $.trim($("#upStartTime").val()),
                upEndTime: $.trim($("#upEndTime").val()),
                isKuaidi: $.trim($("#isKuaidi").val()),
                isSource: $.trim($("#isSource").val()),
                liansuoid: $.trim($("#liansuoid").val()) == '' || $.trim($("#liansuoid").val()) == null ? $.trim($("#teamId").val()) : $.trim($("#liansuoid").val()),
                isSpellgroup: $.trim($("#isSpellgroup").val()),
                ismiaosha: $.trim($("#ismiaosha").val()),
                productType: $("#productType").val(),
            };
        },
        // //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
        // queryParamsType = 'limit' ,返回参数必须包含
        // limit, offset, search, sort, order 否则, 需要包含:
        // pageSize, pageNumber, searchText, sortName,
        // sortOrder.
        // 返回false将会终止请求
        columns: [
            {
                checkbox: true
            },
            {
                field: 'displayorder', // 列字段名
                title: '排序',// 列标题
                formatter: function (value, row, index) {
                    var title = row.title;
                    var str = '';
                    if (flag == 1) {
                        if (row.productId == null || row.productId == '') {
                            // 如果是商户自己新增商品
                            str += '<button class="btn btn-xs btn-warning" onclick="showDisplayorder(\'' + row.id + '\',\'' + row.title + '\',\'' + row.productId + '\')">' + value + '</button>';
                        } else {
                            str += '<span>' + value + '</span>';
                        }
                    } else {
                        str = '<span class="btn btn-xs btn-warning">' + value + '</span>';
                    }

                    return str;
                }
            },
            {
                field: 'id', // 列字段名
                title: 'ID' // 列标题
            },
            {
                field: 'title',
                title: '商品标题'
            },
            {
                field: 'liansuoid',
                title: '是否是门店商品',
                formatter: function (value, row, index) {
                    if (row.liansuoid != "") {
                        return '是(' + "门店:" + row.lsname + " id:" + row.liansuoid + ')';
                    } else {
                        return '否';
                    }

                }
            },
            {
                field: 'thumb',
                title: '商品图片',
                formatter: function (value, row, index) {
                    return '<img style="width:100px;height:80px" src=' + value + '>';
                }
            },
            {
                field: 'unit',
                title: '单位'
            },
            {
                field: 'productPackageFlag',
                title: '商品类型',
                formatter: function (value, row, index) {
                    if (value == 0) {
                        return "<span class='label label-danger'>单品</span>";
                    }else if(value == 1){
                        return "<span class='label label-danger'>套餐</span>";
                    }
                }
            },
            {
                field: '',
                title: '商品属性',
                formatter: function (value, row, index) {
                    var properties = "";
                    if (flag == 1) {
                        // if (row.iszhicai == 1) {
                        //     properties += '<a title="直采"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'iszhicai\',\'\')">直</button></a>';
                        // } else {
                        //     properties += '<a title="直采"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'iszhicai\',\'\')">直</button></a>';
                        // }
                        if(row.productType == 6){
                            if (row.isziti == 1) {
                                properties += '<a title="自提"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isziti\',\'\')">提</button></a>';
                            } else {
                                properties += '<a title="自提"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isziti\',\'\')">提</button></a>';
                            }
                            if (row.istangshi == 1) {
                                properties += '<a title="堂食"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'istangshi\',\'\')">堂</button></a>';
                            } else {
                                properties += '<a title="堂食"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'istangshi\',\'\')">堂</button></a>';
                            }
                            if (row.iswaimai == 1) {
                                properties += '<a title="外卖"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'iswaimai\',\'\')">外</button></a>';
                            } else {
                                properties += '<a title="外卖"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'iswaimai\',\'\')">外</button></a>';
                            }
                        }else{
                            if (row.isnew == 1) {
                                properties += '<a title="新上"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isnew\',\'\')">新</button></a>';
                            } else {
                                properties += '<a title="新上"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isnew\',\'\')">新</button></a>';
                            }

                            /*if (row.isbig == 1) {
                                properties += '<a title="大件"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isbig\')">大</button></a>';
                            } else {
                                properties += '<a title="大件"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isbig\')">大</button></a>';
                            }*/
                            if (row.ishot == 1) {
                                properties += '<a title="爆款"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'ishot\',\'\')">爆</button></a>';
                            } else {
                                properties += '<a title="爆款"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'ishot\',\'\')">爆</button></a>';
                            }
                            if (row.ismao == 1) {
                                properties += '<a title="特卖"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'ismao\',\'\')">特</button></a>';
                            } else {
                                properties += '<a title="特卖"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'ismao\',\'\')">特</button></a>';
                            }
                        }

                        // if (row.isfanchang == 1) {
                        //     properties += '<a title="返场"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isfanchang\',\'\')">返</button></a>';
                        // } else {
                        //     properties += '<a title="返场"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isfanchang\',\'\')">返</button></a>';
                        // }
                        /*if (row.isgerida == 1) {
                            properties += '<a title="隔日达"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isgerida\',\'\')">隔</button></a>';
                        } else {
                            properties += '<a title="隔日达"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isgerida\',\'\')">隔</button></a>';
                        }*/
                        /*if (row.isrecommand == 1) {
                            properties += '<a title="推荐"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isrecommand\')">推</button></a>';
                        } else {
                            properties += '<a title="推荐"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isrecommand\')">推</button></a>';
                        }*/
                        /*if (row.isdiscount == 1) {
                            properties += '<a title="促销"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isdiscount\')">促</button></a>';
                        } else {
                            properties += '<a title="促销"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isdiscount\')">促</button></a>';
                        }*/
                        // if (row.ismiaosha == 1) {
                        //     properties += '<a title="秒杀"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'ismiaosha\',\'\')">秒</button></a>';
                        // } else {
                        //     properties += '<a title="秒杀"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'ismiaosha\',\'\')">秒</button></a>';
                        // }
                        // if (row.islimited == 1) {
                        //     properties += '<a title="限量"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'islimited\',\'\')">限</button></a>';
                        // } else {
                        //     properties += '<a title="限量"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'islimited\',\'\')">限</button></a>';
                        // }
                        //
                        // if (row.isfashi == 1) {
                        //     properties += '<a title="假一罚十"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isfashi\',\'\')">假</button></a>';
                        // } else {
                        //     properties += '<a title="假一罚十"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isfashi\',\'\')">假</button></a>';
                        // }
                        // if (row.iszhutihuakuang == 1) {
                        //     properties += '<a title="主题画框"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'iszhutihuakuang\',\'\')">主</button></a>';
                        // } else {
                        //     properties += '<a title="主题画框"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'iszhutihuakuang\',\'\')">主</button></a>';
                        // }
                        // if (row.isbig == 1) {
                        //     properties += '<a title="包邮"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isbig\',\'\')">包</button></a>';
                        // } else {
                        //     properties += '<a title="包邮"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isbig\',\'\')">包</button></a>';
                        // }
                        // if (row.isvip == 1) {
                        //     properties += '<a title="会员"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isvip\',\'\')">vip</button></a>';
                        // } else {
                        //     properties += '<a title="会员"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isvip\',\'\')">vip</button></a>';
                        // }
                        // if (row.isKuaidi == 1) {
                        //     properties += '<a title="快递直发"><button class="btn btn-xs btn-info" onclick="updateProduct(' + row.id + ',\'isKuaidi\',\'\')">快</button></a>';
                        // } else {
                        //     properties += '<a title="快递直发"><button class="btn btn-xs btn-default"   onclick="updateProduct(' + row.id + ',\'isKuaidi\',\'\')">快</button></a>';
                        // }
                        // if (row.ispresell == 1) {
                        //     properties += '<a title="预售"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'ispresell\',\'\')">预</button></a>';
                        // } else {
                        //     properties += '<a title="预售"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'ispresell\',\'\')">预</button></a>';
                        // }
                    } else {
                        // if (row.iszhicai == 1) {
                        //     properties += '<a title="直采"><button class="btn btn-xs btn-info ">直</button></a>';
                        // } else {
                        //     properties += '<a title="直采"><button class="btn btn-xs btn-default " >直</button></a>';
                        // }
                        if(row.productType == 6){
                            if (row.isziti == 1) {
                                properties += '<a title="自提"><button class="btn btn-xs btn-info " >提</button></a>';
                            } else {
                                properties += '<a title="自提"><button class="btn btn-xs btn-default " >提</button></a>';
                            }

                            if (row.istangshi == 1) {
                                properties += '<a title="堂食"><button class="btn btn-xs btn-info " >堂</button></a>';
                            } else {
                                properties += '<a title="堂食"><button class="btn btn-xs btn-default ">堂</button></a>';
                            }
                            if (row.iswaimai == 1) {
                                properties += '<a title="外卖"><button class="btn btn-xs btn-info ">外</button></a>';
                            } else {
                                properties += '<a title="外卖"><button class="btn btn-xs btn-default ">外</button></a>';
                            }
                        }else{
                            if (row.isnew == 1) {
                                properties += '<a title="新上"><button class="btn btn-xs btn-info " >新</button></a>';
                            } else {
                                properties += '<a title="新上"><button class="btn btn-xs btn-default " >新</button></a>';
                            }

                            if (row.ishot == 1) {
                                properties += '<a title="爆款"><button class="btn btn-xs btn-info " >爆</button></a>';
                            } else {
                                properties += '<a title="爆款"><button class="btn btn-xs btn-default ">爆</button></a>';
                            }
                            if (row.ismao == 1) {
                                properties += '<a title="特卖"><button class="btn btn-xs btn-info ">特</button></a>';
                            } else {
                                properties += '<a title="特卖"><button class="btn btn-xs btn-default ">特</button></a>';
                            }
                        }


                        // if (row.isfanchang == 1) {
                        //     properties += '<a title="返场"><button class="btn btn-xs btn-info ">返</button></a>';
                        // } else {
                        //     properties += '<a title="返场"><button class="btn btn-xs btn-default ">返</button></a>';
                        // }
                        /*if (row.isgerida == 1) {
                            properties += '<a title="隔日达"><button class="btn btn-xs btn-info ">隔</button></a>';
                        } else {
                            properties += '<a title="隔日达"><button class="btn btn-xs btn-default ">隔</button></a>';
                        }*/
                        // if (row.ismiaosha == 1) {
                        //     properties += '<a title="秒杀"><button class="btn btn-xs btn-info ">秒</button></a>';
                        // } else {
                        //     properties += '<a title="秒杀"><button class="btn btn-xs btn-default ">秒</button></a>';
                        // }
                        // if (row.islimited == 1) {
                        //     properties += '<a title="限量"><button class="btn btn-xs btn-info ">限</button></a>';
                        // } else {
                        //     properties += '<a title="限量"><button class="btn btn-xs btn-default ">限</button></a>';
                        // }
                        //
                        // if (row.isfashi == 1) {
                        //     properties += '<a title="假一罚十"><button class="btn btn-xs btn-info ">假</button></a>';
                        // } else {
                        //     properties += '<a title="假一罚十"><button class="btn btn-xs btn-default ">假</button></a>';
                        // }
                        // if (row.iszhutihuakuang == 1) {
                        //     properties += '<a title="主题画框"><button class="btn btn-xs btn-info ">主</button></a>';
                        // } else {
                        //     properties += '<a title="主题画框"><button class="btn btn-xs btn-default ">主</button></a>';
                        // }
                        // if (row.isbig == 1) {
                        //     properties += '<a title="包邮"><button class="btn btn-xs btn-info">包</button></a>';
                        // } else {
                        //     properties += '<a title="包邮"><button class="btn btn-xs btn-default">包</button></a>';
                        // }
                        // if (row.isvip == 1) {
                        //     properties += '<a title="会员"><button class="btn btn-xs btn-info">vip</button></a>';
                        // } else {
                        //     properties += '<a title="会员"><button class="btn btn-xs btn-default">vip</button></a>';
                        // }
                        // if (row.isTeamBuy == 1) {
                        //     properties += '<a title="门店采购"><button class="btn btn-xs btn-info">团</button></a>';
                        // } else {
                        //     properties += '<a title="门店采购"><button class="btn btn-xs btn-default">团</button></a>';
                        // }
                        // if (row.isKuaidi == 1) {
                        //     properties += '<a title="快递直发"><button class="btn btn-xs btn-info">快</button></a>';
                        // } else {
                        //     properties += '<a title="快递直发"><button class="btn btn-xs btn-default">快</button></a>';
                        // }
                        // if (row.ispresell == 1) {
                        //     properties += '<a title="预售"><button class="btn btn-xs btn-info">预</button></a>';
                        // } else {
                        //     properties += '<a title="预售"><button class="btn btn-xs btn-default">预</button></a>';
                        // }
                    }

                    return properties;
                }
            },
            // {
            //     field: 'marketprice',
            //     title: '价格'
            // },
            // {
            //     field: 'costprice',
            //     title: '成本价'
            // },
            // {
            //     field: 'headcommission',
            //     title: '佣金'
            // },
            {
                field: 'salesreal',
                title: '销量'
            },
            {
                field: 'total',
                title: '库存',
                formatter: function (value, row, index) {
                    var title = row.title;
                    var str = '';
                    // if (flag == 1) {
                    // if (row.productId == null || row.productId == '') {
                    // 如果是商户自己新增商品
                    str += '<button class="btn btn-xs btn-warning" onclick="showStockTotal(\'' + row.id + '\',\'' + title + '\',\'' + row.productId + '\')">' + value + '</button>';
                    // } else {
                    //     str += '<span>' + value + '</span>';
                    // }
                    // } else {
                    //     str = '<span class="btn btn-xs btn-warning">' + value + '</span>';
                    // }

                    return str;
                }
            },
            // {
            //     field: 'status',
            //     title: '状态',
            //     formatter: function (value, row, index) {
            //         if (flag == 1) {
            //             if (value == 0) {
            //                 return "<button class='btn btn-sm btn-success pro' onclick='updateProduct(" + row.id + ",\"status\", " + row.productId + ")'>下架</button>";
            //             }
            //             if (value == 1) {
            //                 return "<button class='btn btn-sm btn-info pro' onclick='updateProduct(" + row.id + ",\"status\", " + row.productId + ")'>上架</button>";
            //             }
            //             if (value == 2) {
            //                 return "<span class='label label-default'>定时上架</span>";
            //             }
            //         } else {
            //             if (value == 0) {
            //                 return "<span class='btn btn-sm btn-success'>下架</span>";
            //             }
            //             if (value == 1) {
            //                 return "<span class='btn btn-sm btn-info'>上架</span>";
            //             }
            //             if (value == 2) {
            //                 return "<span class='label label-default'>定时上架</span>";
            //             }
            //         }
            //
            //     }
            // },
            // {
            //     field: 'productType',
            //     title: '商品类型',
            //     formatter: function (value, row, index) {
            //         if (value == 1) {
            //             return "<span class='label label-primary'>预售商品</span>";
            //         } else if (value == 2) {
            //             return "<span class='label label-success'>拼团商品</span>";
            //         } else if (value == 3) {
            //             return "<span class='label label-info'>秒杀商品</span>";
            //         } else if (value == 4) {
            //             return "<span class='label label-warning'>预约商品</span>";
            //         } else if (value == 5) {
            //             return "<span class='label label-danger'>积分兑换</span>";
            //         } else if (value == 6) {
            //             return "<span class='label label-danger'>外卖商品</span>";
            //         } else if (value == 7) {
            //             return "<span class='label label-danger'>堂食商品</span>";
            //         } else if (value == 8) {
            //             return "<span class='label label-danger'>自提商品</span>";
            //         } else if (value == 9) {
            //             return "<span class='label label-danger'>合伙人套餐</span>";
            //         } else {
            //             return "<span class='label label-default'>普通商品</span>";
            //         }
            //     }
            // },
            // {
            //     field: 'timestart',
            //     title: '上架时间'
            // },
            // {
            //     field: 'timeend',
            //     title: '下架时间'
            // },
            {
                field: 'timestart',
                title: '开售时间'
            },
            {
                field: 'timeend',
                title: '停售时间'
            },
            {
                field: 'auditing',
                title: '审核状态',
                formatter: function (value, row, index) {
                    if (value == 1) {
                        return "<span class='label label-info'>审核通过</span>";
                    } else {
                        return "<span class='label label-danger'>未审核</span>";
                    }

                }
            },
            {
                title: '操作',
                field: 'id',
                align: 'center',
                formatter: function (value, row, index) {
                    if (flag == 1) {
                        var e = '<a class="btn btn-primary btn-sm '
                            + s_edit_h
                            + '" href="#" mce_href="#" title="编辑" onclick="edit(\''
                            + value
                            + '\')"><i class="fa fa-edit"></i>编辑</a> ';

                        var d = '<a class="btn btn-warning btn-sm '
                            + s_remove_h
                            + '" href="#" title="删除"  mce_href="#" onclick="remove(\''
                            + value
                            + '\')"><i class="fa fa-remove"></i>删除</a> ';

                        if (row.productId == "") {
                            var c = '<a class="btn btn-success btn-sm '
                                + s_copy_h
                                + '" href="#" title="复制"  mce_href="#" onclick="showProductCopy(\''
                                + value
                                + '\',0)"><i class="fa fa-edit"></i>复制</a> ';
                            return e + d + c;
                        }
                        return e + d;
                    }
                    // if (flag == 0) {
                    //     var e = '<a class="btn btn-primary btn-sm '
                    //         + s_edit_h
                    //         + '" href="#" mce_href="#" title="详情" onclick="detailReadonly(\''
                    //         + value
                    //         + '\')"><i class="fa fa-edit"></i>详情</a> ';
                    //     return e;
                    // }
                }
            }],
        onClickCell: function (field, value, row, $element) {
            $element.attr('contenteditable', true);
            $element.blur(function () {
                var index = $element.parent().data('index');
                var tdValue = $element.html();

                saveData(index, field, tdValue);
            })
        }
    });

    function saveData(index, field, value) {
        $('#productTable').bootstrapTable('updateCell', {
            index: index,       //行索引
            field: field,       //列名
            value: value        //cell值
        })
    }

}

function reLoad() {
    $('#productTable').bootstrapTable('refresh');
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/remove",
            type: "post",
            data: {
                'id': id
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

function showProductCopy(productId, isBatch) {
    if (isBatch == 1) {
        var rows = $('#productTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
        if (rows.length === 0) {
            layer.msg("请选择要复制的数据");
            return;
        }
    }
    $("#copyProductId").val(productId);
    var teamId = $("#teamId").val();
    if (teamId != '' && teamId != null) {//门店
        $("#copyTitle").text('确定要复制选中的记录？');
    }
    $("#modal-copy-product").modal();
    $("#productType").val("");
    $("#store").val("");
    $("#storeIds").val("");
    $("#centre").val("");
    $("#centreIds").val("");

    $("#isBatch", isBatch);
    if (isBatch == 0) {
        $("#copyButton").show();
        $("#batchCopyButton").hide();
    } else {
        $("#copyButton").hide();
        $("#batchCopyButton").show();
    }
}

function copy() {
    var id = $("#copyProductId").val();
    var flag = $("#flag").val();
    var productType = $("#productType").val();
    var teamId = '';
    var centerId = '';
    // debugger;
    //如果是平台，需要传centerId和teamID，
    if (flag == 0 || flag == '0') {
        centerId = $("#centreIds").val();
    }
    //如果是center，只需要传teamId
    else if ((flag == 1 || flag == '1') && (teamId != '' || teamId != null)) {
        teamId = $("#storeIds").val();
    }

    //如果是team，不需要传
    $.ajax({
        url: prefix + "/copy",
        type: "post",
        data: {
            'id': id,
            'centerId': centerId,
            'teamId': teamId,
            'productType':productType
        },
        beforeSend: function (request) {
            index = layer.load();
        },
        success: function (r) {
            if (r.code == 0) {
                layer.close(index);
                layer.closeAll();
                layer.msg(r.msg);
                reLoad();
            } else {
                layer.msg(r.msg);
            }
            var Modal = $('#modal-copy-product');
            Modal.modal('hide');
        }
    });
}

function batchCopy() {
    var rows = $('#productTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length === 0) {
        layer.msg("请选择要复制的数据");
        return;
    }
    var teamId = '';
    var centerId = '';
    var productType = $("#productType").val();
    // debugger;
    //如果是平台，需要传centerId和teamID，
    if (flag == 0 || flag == '0') {
        centerId = $("#centreIds").val();
    }
    //如果是center，只需要传teamId
    else if ((flag == 1 || flag == '1') && (teamId != '' || teamId != null)) {
        teamId = $("#storeIds").val();
    }
    layer.confirm("确认要复制选中的'" + rows.length + "'条数据吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        var ids = [];
        // 遍历所有选择的行数据，取每条数据对应的ID
        $.each(rows, function (i, row) {
            ids[i] = row['id'];
        });
        $.ajax({
            type: 'POST',
            data: {
                "ids": ids,
                'centerId': centerId,
                'teamId': teamId,
                'productType':productType
            },
            url: prefix + '/copyBatch',
            success: function (r) {
                if (r.code === 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }

                var Modal = $('#modal-copy-product');
                Modal.modal('hide');
            }
        });
    }, function () {
    });
}

function batchRemove() {
    var rows = $('#productTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要删除的数据");
        return;
    }
    layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        var ids = new Array();
        // 遍历所有选择的行数据，取每条数据对应的ID
        $.each(rows, function (i, row) {
            ids[i] = row['id'];
        });
        $.ajax({
            type: 'POST',
            data: {
                "ids": ids
            },
            url: prefix + '/batchRemove',
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function () {
    });
}

function add() {
    // iframe层
    layer.open({
        id: 'centre_add',
        type: 2,
        title: '新建直播',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['60%', '80%'],
        content: prefix + '/toAdd' // iframe的url
    });
}

function edit(id) {
    layer.open({
        id: 'productCentre_edit',
        type: 2,
        title: '修改商品',
        maxmin: true,
        shadeClose: false,
        area: ['100%', '100%'],
        content: prefixRestaurant + '/toEdit/' + id, // iframe的url
        end: function () {
            reLoad();
        }
    });
}

function detailReadonly(id) {
    layer.open({
        id: 'productCentre_detail',
        type: 2,
        title: '商品详情',
        maxmin: true,
        shadeClose: false,
        area: ['90%', '90%'],
        content: prefix + '/detailReadonly/' + id, // iframe的url
        end: function () {
            reLoad();
        }
    });
}

var selectProduct = [];

//选择商品
function select_goods(id, title) {
    var isHas = false;
    for (var i = 0; i < selectProduct.length; i++) {
        if (id == selectProduct[i]) {
            isHas = true;
            selectProduct.splice(i, 1);
        }
    }
    if (isHas) {
        $('.sel' + id).removeClass("fa-check fa-check1")
        $('.sel' + id).addClass("fa-plus")
    } else {
        selectProduct.push(id);
        $('.sel' + id).removeClass("fa-plus")
        $('.sel' + id).addClass("fa-check fa-check1")
    }
}

var get_goods_url = "/product/manage/allProduct";

function get_goods() {
    var idOrName = $("#mgkey").val();
    $.ajax({
        url: get_goods_url,
        type: "get",
        data: {"idOrName": idOrName},
        dataType: "json",
        success: function (ret) {
            if (ret != null && ret.length > 0) {
                var html = '';
                for (var i = 0; i < ret.length; i++) {
                    html += '<tr><td>' + ret[i].id + '</td><td><img src=' + ret[i].thumb + ' style="width:50px;height:50px;"></td>' +
                        '<td>' + ret[i].title + '</td>' +
                        '<td><div class="hidden-sm hidden-xs action-buttons" onclick="select_goods(\'' + ret[i].id + '\');">' +
                        '<a title="添加" ><i style="font-size:130%;color:#DD5A43;" class="fa fa-plus sel' + ret[i].id + '"></i></a>' +
                        '</div>' +
                        '</td></tr>';
                }
                $("#ajax-data").html(html);
            }
        }
    });
}

//选择商品保存
function save() {
    $.ajax({
        url: '/product/centre/save',
        contentType: "application/json",
        dataType: "json",
        type: 'POST',
        data: JSON.stringify(selectProduct),
        success: function (result) {
            if (result.code == 0) {
                layer.alert("保存成功", {icon: 6});
            } else {
                layer.alert("保存失败，请联系管理员", {icon: 5});
            }
        }
    })
}

/**
 * 更新商品
 * @param id：商品id
 * @param column：更新的字段
 */
function updateProduct(id, column, productId) {
    if (productId != null && productId != '') {
        layer.msg("该商品属于商品库，不能更新此项", {icon: 5});
        return;
    }
    $('.pro').attr('disabled', true);
    $.ajax({
        url: '/product/centre/btnUpdate',
        type: 'POST',
        data: {"id": id, "column": column},
        success: function (result) {
            if (result.code == 0) {
                $('#productTable').bootstrapTable('refresh');
            } else {
                layer.alert("更新失败，请联系管理员", {icon: 5});
            }
        }
    })
}

// 打开修改库存，弹框
function showStockTotal(id, title, productId) {
    $("#productTitle").text(title);
    $("#productId").val(id);
    $("#modal-teams").modal();
}

//打开修改排序，弹框
function showDisplayorder(id, title, productId) {
    $("#productTitle").text(title);
    $("#productId").val(id);
    $("#modal-displayorder-teams").modal();
}

//修改库存
function updateTotal() {
    var total = $("#total").val();
    var id = $("#productId").val();
    $.ajax({
        url: '/product/centre/updateTotal',
        type: 'POST',
        data: {"id": id, "total": total},
        success: function (result) {
            if (result.code == 0) {
                $('#productTable').bootstrapTable('refresh');
                var Modal = $('#modal-teams');
                Modal.modal('hide');
                $('.modal-backdrop').remove();
            } else {
                if (result.msg != null || result.msg != '') {
                    layer.alert(result.msg, {icon: 5});
                } else {
                    layer.alert("更新失败，请联系管理员", {icon: 5});
                }
            }
        }
    })
}

//修改排序
function updateDisplayorder() {
    var displayorder = $("#displayorder").val();
    var id = $("#productId").val();
    $.ajax({
        url: '/product/centre/updateDisplayorder',
        type: 'POST',
        data: {"id": id, "displayorder": displayorder},
        success: function (result) {
            if (result.code == 0) {
                $('#productTable').bootstrapTable('refresh');
                var Modal = $('#modal-displayorder-teams');
                Modal.modal('hide');
                $('.modal-backdrop').remove();
            } else {
                if (result.msg != null || result.msg != '') {
                    layer.alert(result.msg, {icon: 5});
                } else {
                    layer.alert("更新失败，请联系管理员", {icon: 5});
                }
            }
        }
    })
}

function toSelectProduct() {
    layer.open({
        id: 'select_product',
        type: 2,
        title: '选择商品',
        maxmin: true,
        shadeClose: false,
        area: ['95%', '90%'],
        content: prefix + '/toSelectProduct', // iframe的url
        end: function () {
            reLoad();
        }
    });
}

function inport() {
    var formData = new FormData();
    var name = $("#excelFile").val();
    if (name == null || name == '') {
        layer.msg("请选择文件需要上传的文件", {icon: 7});
        return;
    }
    layer.confirm('确认要一键导入吗？', {
        btn: ['确定', '取消']
    }, function () {
        formData.append("file", $("#excelFile")[0].files[0]);
        formData.append("name", name);//这个地方可以传递多个参数
        $.ajax({
            url: '/product/restaurant/inportRestaurantExcel',
            type: 'POST',
            async: false,
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            beforeSend: function () {
                console.log("正在进行，请稍候");
            },
            success: function (responseStr) {
                if (responseStr.code == 0) {
                    layer.msg("导入成功");
                } else {
                    if (responseStr.msg != null || responseStr.msg != '') {
                        layer.alert(responseStr.msg, {icon: 5});
                    } else {
                        layer.msg("导入失败");
                    }
                }
            }
        });
    });
}


/**
 * 导出
 */
function exportProductCentre() {
    var startDate = $.trim($("#startDate").val());
    var endDate = $.trim($("#endDate").val());
    var title = $.trim($("#productName").val());
    var status = $.trim($("#type").val());
    var pcate = $.trim($("#pcate").val());
    var ccate = $.trim($("#ccate").val());
    var supplierId = $.trim($("#supply").val());
    var centreId = $("*[name='centreId']").val();
    var baseId = $.trim($("#baseId").val());
    var upStartTime = $.trim($("#upStartTime").val());
    var upEndTime = $.trim($("#upEndTime").val());
    var isKuaidi = $.trim($("#isKuaidi").val());
    var isSpellgroup = $.trim($("#isSpellgroup").val());
    // if (upStartTime == null || upStartTime == '' || upEndTime == null || upEndTime == '') {
    //     layer.msg("请选择时间");
    //     return;
    // }
    window.location.href = prefixRestaurant + "/exportProductCentre?startDate=" + startDate + "&endDate=" + endDate
        + "&title=" + title + "&status=" + status + "&pcate=" + pcate + "&ccate=" + ccate + "&supplierId=" + supplierId
        + "&centreId=" + centreId + "&baseId=" + baseId + "&upStartTime=" + upStartTime + "&upEndTime=" + upEndTime +
        "&isKuaidi" + isKuaidi + "&isSpellgroup=" + isSpellgroup;
}

function renderCategoryThird(obj) {
    var index = obj.options[obj.selectedIndex].value;
    var html = "<option value='0'>请选择门店</option>";
    if (index == 0) {
        $("#liansuoid").html(html);
    } else {
        $.ajax({
            url: "/commanderList/manage/listCommanders",
            data: {"centreId": index},
            dataType: "json",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].tXiaoqu + data[i].id + '</option>';
                }
                $("#liansuoid").html(html);
            }
        })
    }
}

function renderTeamList(obj) {
    var index = obj.options[obj.selectedIndex].value;
    var html = "<option value='0'>请选择门店</option>";
    if (index == 0) {
        $("#selectedTeam").html(html);
    } else {
        $.ajax({
            url: "/commanderList/manage/listCommanders",
            data: {"centreId": index},
            dataType: "json",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].tXiaoqu + data[i].id + '</option>';
                }
                $("#selectedTeam").html(html);
            }
        })
    }
}

function sortRefund() {
    var rows = $('#productTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length === 0) {
        layer.msg("请选择要更新排序的数据");
        return;
    }
    layer.confirm("确认要更新选中的'" + rows.length + "'条数据的排序吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        var listProduct = [];
        var date = {};
        $.each(rows, function (i, row) {
            var str = row['displayorder'] + "";
            str = str.replace("<span>", "");
            str = str.replace("</span>", "");
            var product = {
                id: row['id'],
                displayorder: row['displayorder'],
            }
            listProduct.push(product);
        })
        date.listProduct = listProduct;
        console.log(JSON.stringify(date))
        $.ajax({
            type: 'POST',
            contentType: "application/json",
            data: JSON.stringify(date),
            url: '/product/centre/updateSort',
            success: function (r) {
                if (r.code === 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function () {
    });

    /**
     * 批量删除
     */
    function batchRemove() {
        var rows = $('#unCheckedTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
        if (rows.length == 0) {
            layer.msg("请选择要删除的数据");
            return;
        }
        layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", {
            btn: ['确定', '取消']
            // 按钮
        }, function () {
            $(".layui-layer-btn0").hide();
            //防止重复点击
            layer.open({type: 1, title: false, closeBtn: false})
            var ids = [];
            // 遍历所有选择的行数据，取每条数据对应的ID
            $.each(rows, function (i, row) {
                ids[i] = row['id'];
            });
            $.ajax({
                type: 'POST',
                data: {
                    "ids": ids
                },
                url: prefix + '/removeBatch',
                success: function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg);
                    } else {
                        layer.msg(r.msg);
                    }
                    //关闭所有弹窗
                    layer.closeAll();
                }
            });
        }, function () {
        });
    }
}

/**
 * 选择商户
 */
function toCentre() {

    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择商户',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: prefix + '/toCentre?idDom=centreIds&nameDom=centre&singleSelect=0&callback=centreCallback' // iframe的url
    });
}

/**
 * 选择门店
 */
function toStore() {

    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择门店',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: prefix + '/toStore?idDom=storeIds&nameDom=store&singleSelect=0&callback=storeCallback' // iframe的url
    });
}

//门店选中回调
function storeCallback(obj) {
    $("#"+obj.nameDom).val(obj.nameStrs);
    $("#"+obj.idDom).val(obj.idStrs);
}

function centreCallback(obj){
    $("#"+obj.nameDom).val(obj.nameStrs);
    $("#"+obj.idDom).val(obj.idStrs);
}

function categoryCloseClick(event){
    if(event == 'one'){ // 一级分类清空
        $("#pcateId").val('')
        $("#pcate").val('')
        $("#ccateId").val('')
        $("#ccate").val('')
    } else { // 二级分类清空
        $("#ccateId").val('')
        $("#ccate").val('')

    }
}

function toCategoryOne(){
    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择顶级分类',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: '/category/manage/toCategory?idDom=pcateId&nameDom=pcate&singleSelect=1&callback=pcateCallback&count=1' // iframe的url
    });
}

function toCategoryTwo(){
    var parentid = $("#pcateId").val();
    if (!parentid) {
        layer.msg("请选择顶级分类");
        return;
    }
    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择下级分类',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: '/category/manage/toCategory?idDom=ccateId&nameDom=ccate&singleSelect=1&callback=pcateCallback&count=2&parentid='+parentid // iframe的url
    });
}

function pcateCallback(obj){
    $("#"+obj.nameDom).val(obj.nameStrs);
    $("#"+obj.idDom).val(obj.idStrs);
    if(obj.count == 1){
        $("#ccate").val("");
        $("#ccateId").val("");
    }
}